package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-16 08:48:27
 * @Description : 树的层序遍历
 * @Version : 1.0
 */
public class Code102Test {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        // 先将根节点塞入队列
        queue.add(root);

        while (!queue.isEmpty()) {
            List<Integer> tmp = new ArrayList<>();

            int size = queue.size();

            while (size > 0) {
                // 每次弹出一个元素，就将这个元素的左右子元素插入到队列的后面
                TreeNode node = queue.poll();
                if (node != null) {
                    tmp.add(node.val);
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                }


                size--;
            }
            list.add(tmp);
        }


        return list;
    }


    @Test
    public void test1() {
        TreeNode root = new TreeNode(3);

        TreeNode node9 = new TreeNode(9);
        TreeNode node20 = new TreeNode(20);

        root.left = node9;
        root.right = node20;

        node20.left = new TreeNode(15);
        node20.right = new TreeNode(7);

        List<List<Integer>> list = List.of(List.of(3), List.of(9, 20), List.of(15, 7));
        assert Objects.equals(list, levelOrder(root));
    }

    @Test
    public void test2() {
        TreeNode root = new TreeNode(1);
        assert Objects.equals(List.of(List.of(1)), levelOrder(root));
    }

    @Test
    public void test3() {
        assert Objects.equals(List.of(), levelOrder(null));
    }
}
